import './style.less';

import * as R from 'ramda';

import { BreadcrumbPlus, Loading } from '@r-magician/ui';
import { Header, RecursionMenu } from '@r-magician/ui';
import { Layout, Modal, message } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import React, { useEffect } from 'react';

import Icon from '../../components/Icon';
import { adminClass } from './config';
import { modifyPassword } from '@/service/auth';
import routes from '../../routes';
import { useAuth } from '../../store/modules/auth';
import { useFloatLayer } from '@r-magician/hooks';
import { useLocation } from 'react-router';
import { useRequest } from 'ahooks';

const renderIcon = ({ icon }) => {
  return !icon || !Icon.iconNames.includes(icon) ? null : <Icon type={icon} />;
};
const validateMessages = {
  required: '${label}不能为空',
};
const comparePassword = ({ getFieldValue }) => ({
  validator(_, value) {
    if (!value || getFieldValue('newPassword') === value) {
      return Promise.resolve();
    }
    return Promise.reject(new Error('密码不一致'));
  },
});

const AdminLayout = ({ children }) => {
  const location = useLocation();

  const { exit, bootstrap, loading, userInfo, menuList } = useAuth();

  useEffect(() => {
    bootstrap();
  }, [bootstrap]);

  const [form] = ProForm.useForm();
  const { run } = useRequest(modifyPassword, {
    manual: true,
  });
  const { visible, confirmLoading, okHandle, open, close } = useFloatLayer({
    onConfirm: async () => {
      try {
        await form.validateFields();
        const data = form.getFieldsValue();
        await run(R.omit(['confirmNewPassword'], data));
        message.success('修改密码成功，请重新登录！');
        exit();
        return Promise.resolve(true);
      } catch (e) {
        return Promise.resolve(false);
      }
    },
    onClose() {
      form.resetFields();
    },
  });

  if (loading) return <Loading />;
  return (
    <Layout className={adminClass()}>
      <Header
        logo="Magician Blueprint"
        username={userInfo?.username}
        dropdownList={[
          { text: '修改密码', handle: open },
          { text: '退出', handle: exit },
        ]}
      />
      <Layout>
        <Modal
          title="修改密码"
          confirmLoading={confirmLoading}
          onOk={okHandle}
          onCancel={close}
          okText="确定"
          cancelText="取消"
          visible={visible}
        >
          <ProForm
            form={form}
            validateMessages={validateMessages}
            submitter={{ render: () => null }}
          >
            <ProFormText.Password
              name="oldPassword"
              label="当前密码"
              rules={[{ required: true }]}
            />
            <ProFormText.Password
              name="newPassword"
              label="新密码"
              rules={[{ required: true }]}
            />
            <ProFormText.Password
              name="confirmNewPassword"
              label="确认新密码"
              rules={[{ required: true }, comparePassword]}
            />
          </ProForm>
        </Modal>
        <Layout.Sider className={adminClass('sider')} theme="light" collapsible>
          <RecursionMenu
            dataSource={menuList}
            isRender={R.T}
            titleKey="name"
            menuProps={{ mode: 'inline' }}
            renderIcon={renderIcon}
          />
        </Layout.Sider>
        <Layout.Content>
          <div className={adminClass('breadcrumb')}>
            <BreadcrumbPlus curRoute={location.pathname} routeConfig={routes} />
          </div>
          <div className={adminClass('main')}>{children}</div>
        </Layout.Content>
      </Layout>
    </Layout>
  );
};

export default AdminLayout;
